import type { JwtPayload, JwtTokenState } from '@/types/pinia'

export const useTokenStore = defineStore('jwtToken', {
	state: (): JwtTokenState => ({
		token: '',
		key: '',
		payload: {} as JwtPayload
	}),
	getters: {
		getToken: state => state.token,
		getPayload: state => state.payload
	},
	actions: {
		updateToken(newToken: string = '') {
			this.token = newToken
			this.payload = {} as JwtPayload
			if (newToken !== '') {
				const jwtArr = newToken.split('.')
				const payloadStrbase64 = jwtArr[1]
				// let payloadStr = Buffer.from(payloadStr, 'base64').toString()
				const payloadStr = atob(payloadStrbase64)
				this.payload = JSON.parse(payloadStr)
			}
		},
		updateKey(newKey: string = '') {
			this.key = newKey
		}
	}
})
